const mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var SALT_WORK_FSCTOR = 10; // 计算强度,越大破解越困难

//数据的更新和查找，以及密码加盐
//定义了一个新的模型，但是此模式还未和users集合有关联
const UserSchema = mongoose.Schema({
    userName : String,
    phone: String,
    password : String,
    showname:false,
    checkStudent:{
      type: Number,
      default: 0
    },
    student:{
      number:{type:Number, default: ''},
      name:{type:String, default: ''},
      grad:{type:String, default: ''},
      major:{type:String ,default: ''},
      email:{type:String, default: ''},
      avatar:{type:String, default: ''},
      teacher:{type:String, default: ''},
      assistant:{type:String, default: ''}
    },
    updateAt: {
      type: Date,
      default: Date.now()
    }
},{
  versionKey: false
});
//每次存入数据时都进行判断
UserSchema.pre('save', function (next) {
    var user = this;
    this.updateAt = Date.now();


     //密码 加盐
  bcrypt.genSalt(SALT_WORK_FSCTOR, function (err, salt) {
    if (err) {
      return next(err);
    }

    bcrypt.hash(user.password, salt, function (err, hash) {
      if (err) {
        return next(err);
      }

      user.password = hash;
      next();
    });
  });
});

UserSchema.methods ={
  comparePassword: function(_password, cb){
    bcrypt.compare(_password, this.password, function (err, isMatch) {
      if (err) {
        return cb(err);
      }
      cb(null, isMatch);
    }) 
  }
};  
  
UserSchema.statics = {
    fetch: function (cb) {
      return this
        .find({})
        .sort('meta.updateAt')
        .exec(cb);
    },
    findById: function (id, cb) {
      return this
        .findOne({_id: id})
        .exec(cb)
    }
};

module.exports = UserSchema;